package com.monkeygroup.mygoplus.view.home.activity.rent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.commit.thing.vo.PropertyCommitVO;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.StringUtil;
import com.monkeygroup.mygoplus.common.utils.image.Images;
import com.monkeygroup.mygoplus.http.PersonHttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.http.ThingsHttpModel;
import com.monkeygroup.mygoplus.thing.vo.MyImageVO;
import com.monkeygroup.mygoplus.thing.vo.RentVO;
import com.monkeygroup.mygoplus.thing.vo.UserVO;
import com.monkeygroup.mygoplus.view.home.activity.CheckOverSizeTextView;
import com.monkeygroup.mygoplus.view.home.activity.MapActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LCW on 2017/5/31.
 */

public class RentShopDetailActivity extends BaseActivity implements OnMapReadyCallback {

    public static void gotoActivity(Activity activity, String type, String parent, String modal, String carport) {
        Intent intent = new Intent(activity,
                RentShopDetailActivity.class);

        Bundle bundle = new Bundle();
        bundle.putSerializable("param", "");
        intent.putExtra("param", bundle);

        //1-租房，2-出售
        intent.putExtra("type", type);
        intent.putExtra("parent", parent);
        //
        intent.putExtra("modal", modal);
        intent.putExtra("carport", carport);

        activity.startActivity(intent);
    }

    private Activity activity;
    private TextView txt_top,txtTitle, txtImgSize, txtPurpose, txtName, txtContact, txtAddr,
            txtSaleprice, txtArea, txtStorey, txtFitting, txtCommunityName;
    private CheckOverSizeTextView text_things_detail_desc;
    private LinearLayout linearLayoutThingsDescOpen,linearLayoutThingsDescClose;
    private Button btnThingsOpenTextOpen,btnThingsOpenTextClose;
    private List<MyImageVO> imageVO;
    private RentVO propertyModel;
    private UserVO userVO;
    //請求
    private ThingsHttpModel httpThingsModel;

    private LayoutInflater mInflater;
    private LinearLayout linearLayoutThingsMap;

    private LinearLayout linear;
    private LinearLayout equipment1;
    private LinearLayout equipment2;
    private LinearLayout feetype1;
    private LinearLayout feetype2;

    private ViewPager viewPager;
    private SimpleDraweeView[] mImageViews;

    private String type,parent,modal,carpot;
    private PropertyCommitVO vo = null;

    //請求參數
    private Map<String, String> params;
    private PersonHttpModel personHttpModel;
    private StringBuffer url;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_rent_shop_detail);
        mInflater = LayoutInflater.from(this);
    }

    @Override
    public void initView() {

        activity=RentShopDetailActivity.this;
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("出租物件");
        txt_top = (TextView) findViewById(R.id.txt_top);

        txtImgSize = (TextView) findViewById(R.id.viewPager_things_all);
        txtPurpose = (TextView) findViewById(R.id.text_things_detail_purpose);
        txtName = (TextView) findViewById(R.id.text_things_detail_name);
        txtContact = (TextView) findViewById(R.id.text_detail_contact);
        txtAddr = (TextView) findViewById(R.id.text_detail_addr);
        txtSaleprice = (TextView) findViewById(R.id.text_things_detail_saleprice);
        txtArea = (TextView) findViewById(R.id.text_things_detail_area);
        txtStorey = (TextView) findViewById(R.id.text_things_detail_propertyage_have);
        txtFitting = (TextView) findViewById(R.id.text_things_detail_fitting);
        txtCommunityName = (TextView) findViewById(R.id.text_things_detail_communityname);
        text_things_detail_desc = (CheckOverSizeTextView) findViewById(R.id.text_things_detail_desc);
        btnThingsOpenTextOpen = (Button) findViewById(R.id.btn_things_open_text_open);
        linearLayoutThingsDescOpen = (LinearLayout) findViewById(R.id.linearLayout_things_desc_open);
        btnThingsOpenTextClose = (Button) findViewById(R.id.btn_things_open_text_close);
        linearLayoutThingsDescClose = (LinearLayout) findViewById(R.id.linearLayout_things_desc_close);
        linear = (LinearLayout) this.findViewById(R.id.linearlayout_things_scrollView);
        equipment1 = (LinearLayout) this.findViewById(R.id.rent_equipment_one);
        equipment2 = (LinearLayout) this.findViewById(R.id.rent_equipment_two);
        feetype1 = (LinearLayout) this.findViewById(R.id.rent_feetype_one);
        feetype2 = (LinearLayout) this.findViewById(R.id.rent_feetype_two);
        linearLayoutThingsMap = (LinearLayout) findViewById(R.id.linearLayout_things_map);


        Intent intent = this.getIntent();
        Bundle bundle =  intent.getExtras();
        type = bundle.getString("type");
        parent= bundle.getString("parent");
        modal= bundle.getString("modal");
        carpot= bundle.getString("carpot");


        imageVO = (List<MyImageVO>) getIntent().getBundleExtra("param").getSerializable("imgModel");
        propertyModel = (RentVO) getIntent().getBundleExtra("param").getSerializable("propertyModel");
        userVO = (UserVO) getIntent().getBundleExtra("param").getSerializable("userVO");
        String param="";
        //发布
        if(imageVO==null) {

            url=new StringBuffer(RequestUrl.savepropertyUrl);

            propertyModel = new RentVO();
            propertyModel.setLat(0);
            propertyModel.setLng(0);

            txt_top.setVisibility(View.VISIBLE);
            txt_top.setText("发布");

            //住宅
            if("1".equals(parent)||"3".equals(parent)||"4".equals(parent)){
                vo = LocalInfo.getHouseProperty(activity,modal);

            }
            //店面
            else if("2".equals(parent)){

                vo=LocalInfo.getShopProperty(activity,modal);

            }
            //車位
            else if("5".equals(parent)){

                // vo=LocalInfo.getCarportProperty(ThingsDetailActivity.this,modal);

            }
            //土地
            else if("6".equals(parent)){
                vo= LocalInfo.getLandProperty(activity,modal);


            }

            String imgtype="";
            //圖片
            if(vo.getPropertyimg_sceimgtype()!=null){
                for(int i=0;i<vo.getPropertyimg_sceimgtype().length;i++){
//                Log.e("getPropertyie==",""+vo.getPropertyimg_sceimgtype()[i]);
                    if(!StringUtil.isBlank(vo.getPropertyimg_sceimgtype()[i])){
                        imgtype=vo.getPropertyimg_sceimgtype()[i];
                    }
                }
                if(vo.getPropertyimg_path1()!=null){

                    for(int i=0;i<vo.getPropertyimg_path1().length;i++) {
                        if (!StringUtil.isBlank(vo.getPropertyimg_path1()[i])) {
                            if(i==0){
                                url.append("?propertyimg_sceimgtype[]="+imgtype);
                            }
                            else{
                                url.append("&propertyimg_sceimgtype[]="+imgtype);
                            }

                            url.append("&propertyimg_path1[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_path3[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_path4[]="+vo.getPropertyimg_path1()[i]);
                            url.append("&propertyimg_width[]="+vo.getPropertyimg_width()[i]);
                            url.append("&propertyimg_height[]="+vo.getPropertyimg_height()[i]);
                            url.append("&propertyimg_size[]="+vo.getPropertyimg_size()[i]);
                            url.append("&propertyimg_name[]="+vo.getPropertyimg_name()[i]);

                        }
                    }
                }

                for(int i=0;i<vo.getPropertyimg_sceimgtype().length;i++) {
                    if (!StringUtil.isBlank(vo.getPropertyimg_sceimgtype()[i])) {



                    }
                }
            }
            getThingsInfo(vo);
            param = "?area="+String.valueOf(vo.getProperty_area())+"&modal="+vo.getProperty_modal();

            vo.setProperty_rent(1);
            params = new HashMap<String, String>();
            vo.toMap(params);

            txt_top.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    personHttpModel.requestUserLogin();
                }
            });
        }
        else{
            setImage(imageVO);
            setThingsInfo(propertyModel);
            setUserInfo(userVO);

            param = "?area="+propertyModel.getArea()+"&modal="+propertyModel.getModal();
        }


        initHorizontalScrollViewRequest(param);
        httpThingsModel.requestThings();

        text_things_detail_desc.setOnOverLineChangedListener(new CheckOverSizeTextView.OnOverSizeChangedListener() {
            @Override
            public void onChanged(boolean isOverSize) {
                if(isOverSize){
                    text_things_detail_desc.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    linearLayoutThingsDescOpen.setVisibility(View.VISIBLE);
                }
            }
        });
        btnThingsOpenTextOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(text_things_detail_desc.isOverSize()){
                    text_things_detail_desc.displayAll();
                    linearLayoutThingsDescOpen.setVisibility(View.GONE);
                    linearLayoutThingsDescClose.setVisibility(View.VISIBLE);
                }else{
                    text_things_detail_desc.hide(15);
                }
            }
        });
        btnThingsOpenTextClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(text_things_detail_desc.isOverSize()){
                    text_things_detail_desc.displayAll();
                }else{
                    text_things_detail_desc.hide(15);
                    linearLayoutThingsDescOpen.setVisibility(View.VISIBLE);
                    linearLayoutThingsDescClose.setVisibility(View.GONE);
                }
            }
        });

        initMap();
    }

    @Override
    public void setListener() {

    }

    @Override
    public void doEvent() {

    }

    private void setImage(List<MyImageVO> imgModel) {
        List<String> imgs = new ArrayList<>();
        for (MyImageVO vo : imgModel) {
            if (vo.getCover() != 1) {
                imgs.add(vo.getPath3());
            }
        }
        viewPager = (ViewPager) findViewById(R.id.viewPager_things_all_img);
        mImageViews = new SimpleDraweeView[imgs.size()];
        for (int i = 0; i < imgs.size(); i++) {
            final SimpleDraweeView imageView = new SimpleDraweeView(this);
            mImageViews[i] = imageView;
            Images.with(this).load(Uri.parse(imgs.get(i).toString())).into(imageView);
        }

        viewPager.setAdapter(new MyAdapter());
        if(mImageViews.length==0){
            txtImgSize.setText(0 + "/" + mImageViews.length);
        }else{
            txtImgSize.setText(1 + "/" + mImageViews.length);
        }
        viewPager.setCurrentItem(0);
        viewpagerListener();
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动  
        //viewPager.setCurrentItem((mImageViews.length)*100);
    }

    private void viewpagerListener() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                txtImgSize.setText((arg0 + 1) + "/" + mImageViews.length);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mImageViews.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(mImageViews[position % mImageViews.length]);
        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }

    }

    private void setThingsInfo(RentVO propertyModel) {
        txtPurpose.setText(propertyModel.getPurpose());
        txtName.setText(propertyModel.getName());
        txtAddr.setText(propertyModel.getAddr());
        txtSaleprice.setText(propertyModel.getRentprice() + " 元");
        txtArea.setText(propertyModel.getLawnarea() + " 坪");
        txtStorey.setText(propertyModel.getPropertyage());
        txtFitting.setText(propertyModel.getFitting());
        txtCommunityName.setText(propertyModel.getCommunityname());
        String [] arr = propertyModel.getShopequip().split(",");
        /*if(arr!=null&&arr.length>0&&!arr.toString().contains("\"")){
            for (int i = 0; i < 8; i++) {
                boolean flg = false;
                for (int j = 0; j < arr.length; j++) {
                    if(i==j){
                        createChildShopequip(arr[j],j);
                        flg = true;
                    }
                }
                if(flg){
                    continue;
                }
                createChildShopequip("",i);
            }
        }*/

        text_things_detail_desc.setText(propertyModel.getDesc());
    }

    private void getThingsInfo(PropertyCommitVO propertyModel) {
        txtPurpose.setText(propertyModel.getProperty_purpose());
        txtName.setText(propertyModel.getProperty_name());
//        txtAddr.setText(propertyModel.getProperty());
//        txtSalePriceTitle.setText("售價");
        txtSaleprice.setText(propertyModel.getProperty_saleprice() + " 萬");
//        txtAreaTitlie.setText("坪數");
        txtArea.setText(propertyModel.getProperty_ownershiparea() + " 坪");
        Log.e("propertyMtyoor()==",""+propertyModel.getProperty_minfloor());
//        txtStoreyTitle.setText("樓層");
        txtStorey.setText(String.valueOf(propertyModel.getProperty_minfloor()));
//        txtCarpotHaveTitel.setText("車位");
//        txtCarpotHave.setText(propertyModel.getProperty_carport() == 0 ? "無" : "有");
//        txtLiftTitle.setText("電梯");
//        txtLift.setText(propertyModel.getProperty_lift() == 0 ? "無" : "有");
//        txtFeeTitle.setText("管理費");
//        txtFee.setText(propertyModel.getProperty_fee() + "元/坪");
//        txtFittingTitle.setText("裝修");
//        getFitting(propertyModel.getProperty_fitting());
//        txtFitting.setText(propertyModel.getProperty_fitting());
//        txtCompletedateTitle.setText("完工日期");
//        txtCompletedate.setText(propertyModel.getProperty_completeyear());
//        txtType.setText(propertyModel.getProperty_purpose());
//        getDirection(propertyModel.getProperty_direction(),txtDirection);
        txtCommunityName.setText(String.valueOf(propertyModel.getProperty_community()));
        //店面相关
//        if("2".equals(parent)){
//            getDirection(propertyModel.getProperty_direction(),txt_detail_direction_item);
//            txt_detail_model_item.setText(propertyModel.getProperty_purpose());
//            txt_detail_road_width_item.setText(propertyModel.getProperty_roadwidth()+"米");
//            txt_detail_width_item.setText(propertyModel.getProperty_width() + "陽臺");
//            txt_detail_width_item.setText(String.format("%s 米 × %s 米",propertyModel.getProperty_width(),propertyModel.getProperty_height()));
//
//            setshopequip(propertyModel.getProperty_shopequip());
//        }
    }



    private void setUserInfo(UserVO userVO) {
        txtContact.setText(userVO.getName() + " " + userVO.getTel());
    }

    private String getPropertyShopequip(int shopequip){
        switch (shopequip) {
            case 1:
                return "客梯";
            case 2:
                return "货梯";
            case 3:
                return "扶梯";
            case 4:
                return "暖气";
            case 5:
                return "空调";
            case 6:
                return "停车位";
            case 7:
                return "水";
            case 8:
                return "燃气";
            case 9:
                return "网络";
            default:
                return "";
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng positon = new LatLng(propertyModel.getLat(), propertyModel.getLng());
        googleMap.addMarker(new MarkerOptions().position(positon).title(""));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(positon));
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("positon", propertyModel.getLat()+"-"+propertyModel.getLng());
                Intent intent = new Intent(RentShopDetailActivity.this,MapActivity.class);
                intent.putExtra("positon",bundle);
                startActivityForResult(intent,1);
            }
        });
    }

    private void initMap(){
        View view = mInflater.inflate(R.layout.map_things_detail,linearLayoutThingsMap, false);
        linearLayoutThingsMap.addView(view);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map_thing_detail);
        mapFragment.getMapAsync(this);
    }

    public void initHorizontalScrollViewRequest(String param) {
        httpThingsModel = new ThingsHttpModel(RequestUrl.thingsbuyUrl + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<RentVO> propertys = gson.fromJson(gson.toJson(property), new TypeToken<List<RentVO>>() {
                        }.getType());

                        for (int i = 0; i < propertys.size(); i++) {
                            if(propertys.get(i).getSeq()==propertyModel.getSeq()){
                                continue;
                            }
                            createChildLinearLayout(propertys.get(i),i);
                        }

                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);

        personHttpModel = new PersonHttpModel(url.toString(),params,new PersonHttpModel.SimpleOnHttpRequestListener(){


            @Override
            public void onRequestFinished(String resultCode, Integer timestamp) {

            }

            @Override
            public void onRequestFinished(String resultCode, int seq, int isbind, String acc) {


            }

            @Override
            public void onRequestFinished(String resultCode, int seq, int flag, String flag_name, int secflag, String secflag_name) {

                Log.e("resultCoderesultCode===",""+"ERROR_OK".equals(resultCode));
                //請求成功
                if("ERROR_OK".equals(resultCode)){
                    Toast.makeText(activity, "发布成功",
                            Toast.LENGTH_SHORT).show();
                    txt_top.setVisibility(View.INVISIBLE);
                    LocalInfo.removeProperty(activity,vo);

                }
                else{

                    Toast.makeText(activity, "发布失败",
                            Toast.LENGTH_SHORT).show();
                }
            }

        },true);
    }

    private void createChildLinearLayout(final RentVO vo, final int i) {
        View view = mInflater.inflate(R.layout.item_things_detail_horizontalscrollview,linear, false);
        SimpleDraweeView imgView = (SimpleDraweeView) view.findViewById(R.id.img_things_horizontalscrollview);
        Images.with(this).load(Uri.parse(vo.getImg())).resize(180,180).into(imgView);
        TextView text1 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_1);
        text1.setText(vo.getName());
        TextView text2 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_2);
        text2.setText("NT$ "+vo.getSaleprice()+"/萬");
        TextView text3 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_3);
        text3.setText("坪數:"+vo.getLawnarea()+" 坪");
        TextView text4 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_4);
        text4.setText("層樓:"+vo.getStorey());
        linear.addView(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String param ="?seq="+vo.getSeq();
                initDetailRequest(param);
                httpThingsModel.requestThings();
            }
        });
    }

    private void createChildShopequip(String text,int index){
        if(index<4){
            View view = mInflater.inflate(R.layout.item_shopequip,equipment1, false);
            ((TextView)view.findViewById(R.id.Text_rent_equipment)).setText(getPropertyShopequip(Integer.parseInt(text)));
            if(index==0||text.length()==0){
                view.findViewById(R.id.rent_equipment_one_).setVisibility(View.GONE);
            }
            equipment1.addView(view);
        }else if(index>=4){
            View view = mInflater.inflate(R.layout.item_shopequip,equipment2, false);
            ((TextView)view.findViewById(R.id.Text_rent_equipment)).setText(text);
            if(index==4||text.length()==0){
                view.findViewById(R.id.rent_equipment_one_).setVisibility(View.GONE);
            }
            equipment2.addView(view);
        }

    }

    private void createChildfeetype(String text,int index){
        if(index<4){
            View view = mInflater.inflate(R.layout.item_shopequip,feetype1, false);
            ((TextView)view.findViewById(R.id.Text_rent_equipment)).setText(text);
            feetype1.addView(view);
        }else if(index>4){
            View view = mInflater.inflate(R.layout.item_shopequip,feetype2, false);
            ((TextView)view.findViewById(R.id.Text_rent_equipment)).setText(text);
            feetype2.addView(view);
        }

    }

    public void initDetailRequest(String param) {
        httpThingsModel = new ThingsHttpModel(RequestUrl.getPropertyUrl + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<MyImageVO> imgModel = gson.fromJson(gson.toJson(img), new TypeToken<List<MyImageVO>>() {
                        }.getType());
                        RentVO propertyModel = gson.fromJson(gson.toJson(property), new TypeToken<RentVO>() {
                        }.getType());
                        UserVO userVO = gson.fromJson(gson.toJson(user), new TypeToken<UserVO>() {
                        }.getType());

                        Bundle bundle = new Bundle();
                        bundle.putSerializable("imgModel", (Serializable) imgModel);
                        bundle.putSerializable("propertyModel", propertyModel);
                        bundle.putSerializable("userVO", userVO);
                        Intent intent = new Intent(RentShopDetailActivity.this,RentShopDetailActivity.class);
                        intent.putExtra("param", bundle);
                        RentShopDetailActivity.this.startActivityForResult(intent, 3);
                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);
    }

}